package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"os/signal"
	"syscall"

	"gopkg.in/yaml.v3"
	monproto "gollect/proto"
)

type Config struct {
	CPUInterval      int `yaml:"cpu_interval"`
	MemoryInterval   int `yaml:"memory_interval"`
	DiskInterval     int `yaml:"disk_interval"`
	IOInterval       int `yaml:"io_interval"`
	ProcessInterval  int `yaml:"process_interval"`
	UserInterval     int `yaml:"user_interval"`
	Port             int `yaml:"port"`
	Verbose          bool `yaml:"verbose"`
}

func loadConfig(path string) (*Config, error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	var cfg Config
	dec := yaml.NewDecoder(f)
	if err := dec.Decode(&cfg); err != nil {
		return nil, err
	}
	return &cfg, nil
}

func main() {
	// Parse command line flags
	configPath := flag.String("config", "config.yaml", "Path to configuration file")
	port := flag.Int("port", 50051, "Port to listen on")
	verbose := flag.Bool("verbose", false, "Enable verbose output to print collected information")
	flag.Parse()

	fmt.Println("Starting monitoring client server...")

	// Load configuration
	cfg, err := loadConfig(*configPath)
	if err != nil {
		log.Printf("Failed to load config: %v", err)
		// Use default config if file not found
		cfg = &Config{
			CPUInterval:      1,
			MemoryInterval:   1,
			DiskInterval:     5,
			IOInterval:       5,
			ProcessInterval:  5,
			UserInterval:     5,
			Port:             *port,
			Verbose:          *verbose,
		}
		log.Println("Using default configuration")
	}

	// Override port and verbose if specified via command line
	if *port != 50051 {
		cfg.Port = *port
	}
	if *verbose {
		cfg.Verbose = *verbose
	}

	// Set up signal handling for graceful shutdown
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)

	// Start the gRPC server in a goroutine
	go func() {
		if err := startServer(cfg, cfg.Port); err != nil {
			log.Fatalf("Failed to start server: %v", err)
		}
	}()

	fmt.Printf("Monitoring client server started on port %d\n", cfg.Port)
	if cfg.Verbose {
		fmt.Println("Verbose mode enabled - collected information will be printed")
	}
	fmt.Println("Press Ctrl+C to stop the server")

	// Wait for shutdown signal
	<-sigChan
	fmt.Println("\nShutting down monitoring client server...")
}

func printEnvelope(env *monproto.MonitoringEnvelope) {
	yamlBytes, err := yaml.Marshal(env)
	if err != nil {
		fmt.Println("Failed to marshal envelope to YAML:", err)
		return
	}
	fmt.Println(string(yamlBytes))
}
